package consumer_manager

import (
	"net/http"
	"time"

	"gitee.com/Sxiaobai/gs/gstool"
	"github.com/gin-gonic/gin"
)

// APIServer HTTP API服务器
type APIServer struct {
	manager *Manager
	config  *Config
	logger  *gstool.GsSlog
	engine  *gin.Engine
}

// NewAPIServer 创建API服务器
func NewAPIServer(manager *Manager, config *Config, logger *gstool.GsSlog) *APIServer {
	return &APIServer{
		manager: manager,
		config:  config,
		logger:  logger,
	}
}

// SetupRoutes 设置路由
func (api *APIServer) SetupRoutes(engine *gin.Engine) {
	api.engine = engine
	v1 := engine.Group(api.config.HTTPPrefix)
	{
		v1.POST("/consumer/adjust", api.adjustConsumerCount)
		v1.POST("/consumer/pause", api.pauseConsumers)
		v1.POST("/consumer/toggle-scaling-mode", api.toggleScalingMode)
		v1.GET("/consumer/status", api.getConsumerStatus)
		v1.GET("/consumer/health", api.healthCheck)
	}
}

// StartServer 启动独立HTTP服务器
func (api *APIServer) StartServer() error {
	if !api.config.HTTPEnabled {
		return nil
	}

	api.engine = gin.Default()
	api.SetupRoutes(api.engine)

	api.logger.Infof("HTTP服务器启动在端口: %s", api.config.HTTPPort)
	return api.engine.Run(":" + api.config.HTTPPort)
}

// adjustConsumerCount 调整消费者数量
func (api *APIServer) adjustConsumerCount(c *gin.Context) {
	var req AdjustRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, APIResponse{
			Code:    400,
			Message: "参数错误: " + err.Error(),
		})
		return
	}

	err := api.manager.AdjustCount(req.ConsumerCount)
	if err != nil {
		c.JSON(http.StatusInternalServerError, APIResponse{
			Code:    500,
			Message: "调整消费者数量失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, APIResponse{
		Code:    200,
		Message: "调整消费者数量成功",
		Data:    api.manager.GetStatus(),
	})
}

// pauseConsumers 暂停所有消费者
func (api *APIServer) pauseConsumers(c *gin.Context) {
	err := api.manager.PauseConsumers()
	if err != nil {
		c.JSON(http.StatusInternalServerError, APIResponse{
			Code:    500,
			Message: "暂停消费者失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, APIResponse{
		Code:    200,
		Message: "消费者暂停成功",
		Data:    api.manager.GetStatus(),
	})
}

// getConsumerStatus 获取消费者状态
func (api *APIServer) getConsumerStatus(c *gin.Context) {
	statuses, err := api.manager.dbManager.GetAllStatus()
	if err != nil {
		api.logger.Errof("获取状态失败: %v", err)
		c.JSON(http.StatusInternalServerError, APIResponse{
			Code:    500,
			Message: "获取状态失败: " + err.Error(),
		})
		return
	}

	var statusData []StatusData
	for _, status := range statuses {
		// 只返回当前服务器IP和端口的消费者信息
			if status.ServerIP == api.config.HostIP && status.Port == api.config.HostPort {
				statusData = append(statusData, StatusData{
					CurrentCount:       status.ConsumerCount,
					MaxConsumerCount:   status.MaxConsumerCount,
					SpawnConsumerCount: status.SpawnConsumerCount,
					DepthLimit:         status.DepthLimit,
					ConsumerName:       status.ConsumerName,
					ServerIP:           status.ServerIP,
					Port:               status.Port,
					NSQLookupHost:      status.NSQLookupHost,
					NSQHTTPAddress:     status.NSQHTTPAddress,
					NSQAdminAddress:    status.NSQAdminAddress,
					Topic:              status.Topic,
					Channel:            status.Channel,
						LastUpdate:         status.UpdateTime.Format("2006-01-02 15:04:05"),
					ConsumerRemark:     status.ConsumerRemark,
					ScalingMode:        status.ScalingMode,
				})
			}
	}

	c.JSON(http.StatusOK, APIResponse{
		Code:    200,
		Message: "获取消费者状态成功",
		Data:    statusData,
	})
}

// toggleScalingMode 切换scaling_mode状态
func (api *APIServer) toggleScalingMode(c *gin.Context) {
	err := api.manager.ToggleScalingMode()
	if err != nil {
		c.JSON(http.StatusInternalServerError, APIResponse{
			Code:    500,
			Message: "切换scaling_mode状态失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, APIResponse{
		Code:    200,
		Message: "切换scaling_mode状态成功",
		Data:    api.manager.GetStatus(),
	})
}

// healthCheck 健康检查
func (api *APIServer) healthCheck(c *gin.Context) {
	c.JSON(http.StatusOK, APIResponse{
		Code:    200,
		Message: "服务正常",
		Data: map[string]interface{}{
			"status": "healthy",
			"time":   time.Now().Format("2006-01-02 15:04:05"),
		},
	})
}
